#include <sys/epoll.h>
#include <memory>
#include <iostream>

#include "timer.h"

// 使用测试
int main()
{
    int epfd = epoll_create(1);

    std::unique_ptr<Timer> timer = std::make_unique<Timer>();

    // 添加定时器
    int i = 0;
    timer->AddTimer(1000, [&](const TimerNode& node){
        std::cout << Timer::GetTick() << "ms, node id: " << node.id << ", revoked times: " << ++i << std::endl;
    });

    timer->AddTimer(1000, [&](const TimerNode& node){
        std::cout << Timer::GetTick() << "ms, node id: " << node.id << ", revoked times: " << ++i << std::endl;
    });

    timer->AddTimer(3000, [&](const TimerNode& node){
        std::cout << Timer::GetTick() << "ms, node id: " << node.id << ", revoked times: " << ++i << std::endl;
    });

    // 一直定时执行(没3000毫秒执行一次)
    timer->AddTimer(3000, [&](const TimerNode& node){
        std::cout << Timer::GetTick() << "ms, node id: " << node.id << ", revoked times: " << ++i << std::endl;
    }, 1);

    // 删除定时器
    auto node = timer->AddTimer(2100, [&](const TimerNode& node){
        std::cout << Timer::GetTick() << "ms, node id: " << node.id << ", revoked times: " << ++i << std::endl;
    });
    timer->DelTimer(node);

    std::cout << "now time: " << Timer::GetTick() << "ms" << std::endl;
    epoll_event ev[64] = {0};

    while (true)
    {
        /*
            阻塞等待多久 timeout参数
            -1: 永久阻塞
            0:  立即返回, 没有事件,立即返回,有事件就拷贝到 ev 数组当中
            t > 0: 阻塞等待 t 毫秒, t毫秒都没有事件返回0
            timeout 最近触发的定时任务离当前的时间
        */
        int n = epoll_wait(epfd, ev, sizeof(ev), timer->TimeToSleep());
        for (int i = 0; i < n; i++)
        {
            // ... 处理网络事件
        }

        /* 处理定时事件 */
        timer->CheckTimer();
    }

    return 0;
}